package com.eascs.web.o2o.dc.service;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.web.o2o.dc.dao.DcDao;
import com.eascs.web.o2o.dc.dao.OaDao;
import com.eascs.web.o2o.dc.dao.ServiceDao;
import com.eascs.web.o2o.dc.entity.BasicInformationAfterLoan;
import com.eascs.web.o2o.dc.entity.BasicInformationLoanIng;
import com.eascs.web.o2o.dc.entity.LoanBaseInfoEntity;
import com.eascs.web.o2o.dc.entity.LoanTimeNum;
import com.eascs.web.o2o.dc.entity.O2oPaymentsPlan;
import com.eascs.web.o2o.dc.entity.PaymentsPlan;
import com.eascs.web.o2o.dc.entity.WfStatus;
import com.eascs.web.o2o.scheduler.dao.CrmDao;
import com.eascs.web.o2o.scheduler.entity.HrUnit;
import com.eascs.web.o2o.scheduler.entity.O2oCustomer;
import com.eascs.web.o2o.scheduler.util.Constant;

/**
 * 同步业务系统数据
 * 
 * @author ycz
 *
 */
@Service
public class SynchroDataService {
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private ServiceDao servicedao;
	@Autowired
	private DcDao dcDao;
	@Autowired
	private OaDao oaDao;
	@Autowired
	private CrmDao crmDao;

	/**
	 * 同步贷前数据
	 */
	public void synchroNew() {
		init();
		saveBaseO2oByNew();
		updateLoanAmount();
	}

	/**
	 * 同步业务系统数据--增量同步
	 */
	public void saveBaseO2oByNew() {
		StringBuffer querySql = new StringBuffer();
		querySql.append("SELECT OL.BILL_CODE,OL.LOAN_ID AS CUSTOMER_ID,OL.LOANAPPLY_NO AS LOAN_APPLY_NO,OL.LTD AS OPERATOR_AGENCY," + "OL.OPERATOR_NO,OL.OPERATOR_NAME,OL.REFERRER_NO,OL.REFERRER_NAME,OL.WF_TYPE AS REFUND_STATUS,OL.BANK_LOAN_NAME AS BANKREFUND,"
				+ "OL.BANK_TYPE,OL.LOAN_TYPE,OL.LOAN_TERM,OL.LOANA_MOUNT AS LOAN_AMOUNT,OL.REPAY_MENTWAY AS REPAYMENTWAY,OL.BANK_AMOUNT AS BANK_LOAN_AMOUNT,OL.PAYMENT_TIME AS LOAN_TIME,"
				+ "T.DOCUMENT_TYPE AS DOCUMENT_TYPE,T.DOCUMENT_NO AS IDCARD,T.USER_SURNAME AS CRMOTOLOANERSUR,T.USER_NAME AS CRMOTOLOANER," + "T.USER_FULL_NAME AS CRMOTOLOANERNAME,T.USER_PHONE AS CRMOTOLOANERPHONE,OL.CUSTOMER_TYPE,OL.IS_PLACE_ON_FILE,OL.PLACE_ON_FILE_TIME,"
				+ "OL.CREATE_DATE AS CREATE_TIME,OL.END_DATE AS END_DATE,OL.LOANRATE,OL.DEPOSITRATE AS DEPOSITE_RATE,OL.MANAGEFEERATE AS MANGER_RATE," + "OL.RISK AS RISK_RATE,EX.REC_DEPOSITE AS TOTAL_DEPOSITE,EX.REC_DEPOSITE,EX.RED_DEPOSITE,EX.RETA_DEPOSITE,(EX.RED_DEPOSITE - EX.RETA_DEPOSITE"
				+ ") AS BALANCE_DEPOSITE,EX.REC_MANGER AS TOTAL_MANGER,EX.REC_MANGER,EX.RED_MANGER,EX.RETA_MANAGE AS RETA_MANAGER,(EX.RED_MANGER - RETA_MANAGE)" + " AS BALANCE_MANGER,EX.REC_RISK AS TOTAL_RISK,EX.REC_RISK,EX.RED_RISK,EX.RETA_RISK,(EX.RED_RISK - EX.RETA_RISK) AS BALANCE_RISK,"
				+ "OL.END_BANK_DATE AS END_BANK_DATE FROM O2O_LOANAPPLY OL LEFT JOIN O2O_LOANAPPLY_EXPAND EX ON OL.LOANAPPLY_NO = EX.LOANAPPLY_NO" + " LEFT JOIN O2O_LOAN_USER T ON OL.LOANAPPLY_NO=T.LOANAPPLY_NO " + " AND OL.LOAN_ID=T.LOAN_ID AND T.SPONSOR_TYPE IS NULL AND T.SPOUSE_ID IS NULL"
				+ " WHERE OL.BILL_CODE IS NOT NULL GROUP BY OL.BILL_CODE");
		int pageIndex = 0;
		int insertCount = 0;
		int updateCount = 0;
		int pageSize = 100;
		while (pageIndex >= 0) {
			logger.info("ServiceTask贷前定时任务运行中，正在查询第[{}]页数据", pageIndex);
			SqlPageQuery<LoanBaseInfoEntity> sqlPageQuery = new SqlPageQuery<>(LoanBaseInfoEntity.class, pageSize, pageIndex, querySql.toString());
			PageResult<LoanBaseInfoEntity> results = servicedao.findDataWithPage(sqlPageQuery);
			List<LoanBaseInfoEntity> baseInfoList = results.getData();
			for (LoanBaseInfoEntity baseInfo : baseInfoList) {
				if (StringUtil.isNotBlank(baseInfo.getOperatorAgency())) {
					HrUnit unit = oaDao.findEntity("select hr.PROVINCE from eadb.hr_units hr where hr.unitno=?", HrUnit.class, baseInfo.getOperatorAgency());
					if (unit != null) {
						baseInfo.setOperatorProvince(unit.getProvince());
					}
				}
				if (StringUtils.isNotEmpty(baseInfo.getRefundStatus())) {
					if ("O".equals(baseInfo.getRefundStatus())) {
						baseInfo.setRefundStatus("RUN");
					} else if ("HN".equals(baseInfo.getRefundStatus())) {
						baseInfo.setRefundStatus("CLO");
					}
				}
				baseInfo.setUpdateTime(new Date());
				if (baseInfo.getBillCode().contains("O2O")) {
					baseInfo.setSourceType(0);
				} else {
					baseInfo.setSourceType(1);
				}
				baseInfo.setIslock("N");
				StringBuffer update = new StringBuffer(" UPDATE loan_base_info l SET l.bank_loan_amount =?, l.loan_time =?, l.bankrefund =?, l.bank_type =?, ");
				update.append(" l.loan_amount =?,l.total_deposite =?, l.rec_deposite =?, l.red_deposite =?, l.reta_deposite =?, ");
				update.append(" l.balance_deposite =?, l.total_manger =?, l.rec_manger =?, l.red_manger =?, l.reta_manger =?, ");
				update.append(" l.balance_manger =?, l.total_risk =?, l.rec_risk =?, l.red_risk =?, l.reta_risk =?, ");
				update.append(" l.balance_risk =?,l.loan_type=?,l.refund_status=?,l.repay_mentway=?,l.is_place_on_file=?,l.update_time=?");
				update.append("  WHERE l.bill_code =? ");
				boolean flag = dcDao.excuteSql(update.toString(), baseInfo.getBankLoanAmount(), baseInfo.getLoanTime(), baseInfo.getBankrefund(), baseInfo.getBankType(), baseInfo.getLoanAmount(), baseInfo.getTotalDeposite(), baseInfo.getRecDeposite(), baseInfo.getRedDeposite(),
						baseInfo.getRetaDeposite(), baseInfo.getBalanceDeposite(), baseInfo.getTotalManger(), baseInfo.getRecManger(), baseInfo.getRedManger(), baseInfo.getRetaManger(), baseInfo.getBalanceManger(), baseInfo.getTotalRisk(), baseInfo.getRecRisk(), baseInfo.getRedRisk(),
						baseInfo.getRetaRisk(), baseInfo.getBalanceRisk(), baseInfo.getBillCode(), baseInfo.getLoanType(), baseInfo.getRefundStatus(), baseInfo.getRepayMentway(), baseInfo.getIsPlaceOnFile(), new Date());
				if (flag == false) {
					dcDao.insert(baseInfo);
					insertCount++;
				} else {
					updateCount++;
				}
			}
			pageIndex++;
			if (results.getPageTotal() <= pageIndex) {
				pageIndex = -1;
			}
		}
		logger.info("/****************插入贷前数据条数:[{}]******************************/", insertCount);
		logger.info("/****************更新贷前数据条数:[{}]******************************/", updateCount);
		// 更新贷款人配偶名字
		String updateSql = "UPDATE loan_base_info a SET a.couple_name = ( SELECT b.customer_name FROM o2o_customer b " + "WHERE customer_id=(select mate_id from	o2o_customer c where c.customer_id=a.customer_id)) " + "WHERE a.source_type = 1";
		boolean flag = dcDao.excuteSql(updateSql);
		logger.info("/**********贷前同步更新配偶姓名是否成功:[{}]*********************/", flag);
	}

	/**
	 * 增量--更新第几笔贷款和续贷字段
	 */
	private void updateLoanAmount() {
		logger.info("/****************开始同步续贷和贷款次数字段******************************/");
		String pSql = " select t.bill_code,(select count(1) from loan_base_info l where l.idcard= t.idcard and l.loan_time is not null " + "and l.loan_time<=t.loan_time) num from loan_base_info t where t.loan_time is not null  AND t.loan_num = 0 ";
		List<Object[]> list = dcDao.findObjectsList(pSql);
		logger.info("/*************续贷更新记录数:[{}]*********************/", list.size());
		for (int i = 0; i < list.size(); i++) {
			Object[] b = list.get(i);
			dcDao.excuteSql("update loan_base_info set loan_num=? where bill_code=? ", b[1], b[0]);
		}
		dcDao.excuteSql("update loan_base_info t set t.is_renew_loan = 'Y' where t.loan_num >1");
		dcDao.excuteSql("update loan_base_info t set t.is_renew_loan = 'N' where t.loan_num =1 ");
		logger.info("/****************更新续贷和贷款次数完成******************************/");
	}

	/**
	 * 
	 * 贷中数据--增量同步
	 * 
	 */
	public void saveBaseO2oByLoading() {
		// 查询贷前数据
		logger.info("/****************同步贷中数据******************************/");
		StringBuffer querySql = new StringBuffer();
		querySql.append("SELECT * FROM LOAN_BASE_INFO T WHERE T.REFUND_STATUS IS NOT NULL AND T.SOURCE_TYPE='1'");
		int pageIndex = 0;
		int pageSize = 100;
		int insertCount = 0;
		int updateCount = 0;
		Date updateTime = new Date();
		while (pageIndex >= 0) {
			SqlPageQuery<LoanBaseInfoEntity> sqlPageQuery = new SqlPageQuery<>(LoanBaseInfoEntity.class, pageSize, pageIndex, querySql.toString());
			PageResult<LoanBaseInfoEntity> results = dcDao.findDataWithPage(sqlPageQuery);
			List<LoanBaseInfoEntity> baseInfoList = results.getData();
			for (LoanBaseInfoEntity loanBaseInfoEntity : baseInfoList) {
				String o2oSql = "select * from wf_type_status t where t.loanapply_no=?";
				List<WfStatus> wfList = servicedao.findEntitys(o2oSql, WfStatus.class, loanBaseInfoEntity.getLoanApplyNo());
				if (wfList != null && wfList.size() > 0) {
					BasicInformationLoanIng info = assembleObject(wfList);
					info.setUpdatetime(updateTime);
					info.setLoanapplyno(loanBaseInfoEntity.getLoanApplyNo());
					info.setSourceType(loanBaseInfoEntity.getSourceType());
					info.setBankLoanDate(loanBaseInfoEntity.getLoanTime());
					String updateSql = "UPDATE basic_information_loan_ing t SET t.credit_reporting_date=?,t.credit_over_date=?," + "t.in_exam_ing_date=?,t.in_exam_over_date=?,t.bank_submit_ing_date=?,"
							+ "t.bank_submit_over_date=?,t.bank_loan_date=?,t.source_type=?,t.updatetime=? WHERE t.loanapplyno=?;";
					boolean flag = dcDao.excuteSql(updateSql, info.getCreditReportingDate(), info.getCreditOverDate(), info.getInExamIngDate(), info.getInExamOverDate(), info.getBankSubmitIngDate(), info.getBankSubmitOverDate(), loanBaseInfoEntity.getLoanTime(), loanBaseInfoEntity.getSourceType(),
							updateTime, loanBaseInfoEntity.getLoanApplyNo());
					if (!flag) {
						dcDao.insert(info);
						insertCount++;
					} else {
						updateCount++;
					}
				}
			}
			pageIndex++;
			if (results.getPageTotal() <= pageIndex) {
				pageIndex = -1;
			}
		}
		logger.info("/****************插入贷中数据条数:[{}]******************************/", insertCount);
		logger.info("/****************更新贷中数据条数:[{}]******************************/", updateCount);
		logger.info("/****************同步贷中数据完成******************************/");
	}

	/**
	 * 组装贷中实体
	 * 
	 * @param wfstatus
	 * @return
	 */
	private BasicInformationLoanIng assembleObject(List<WfStatus> wfList) {
		BasicInformationLoanIng infoLoading = new BasicInformationLoanIng();
		if (null != wfList && wfList.size() > 0) {
			for (WfStatus wfStatus : wfList) {
				if ("ZX".equals(wfStatus.getWfType())) {
					infoLoading.setCreditReportingDate(wfStatus.getStartDate());
					infoLoading.setCreditOverDate(wfStatus.getEndDate());
				}
				if ("NS".equals(wfStatus.getWfType())) {
					infoLoading.setInExamIngDate(wfStatus.getStartDate());
					infoLoading.setInExamOverDate(wfStatus.getEndDate());
				}
				if ("BRT".equals(wfStatus.getWfType())) {
					infoLoading.setBankSubmitIngDate(wfStatus.getStartDate());
					infoLoading.setBankSubmitOverDate(wfStatus.getEndDate());
				}
			}
		}
		return infoLoading;
	}

	/**
	 * 
	 * 贷后同步--增量同步
	 * 
	 */
	public void saveBaseO2oByAfter() {
		// 1.增量同步贷后表数据
		updateO2oByAfter();
		// 2.更新贷款次数和第一次放款时间
		updateO2oCustomer();
		// 3.同步逾期数据并修改贷后和贷前数据
		schroOverdue();

	}

	/**
	 * 增量同步贷后数据 和 放款余额
	 * 
	 */
	public void updateO2oByAfter() {
		String sql = "SELECT * FROM LOAN_BASE_INFO T WHERE T.LOAN_TIME IS NOT NULL AND T.ISLOCK='N'";
		int pageIndex = 0;
		int insertCount = 0;
		int updateCount = 0;
		while (pageIndex >= 0) {
			SqlPageQuery<LoanBaseInfoEntity> sqlPageQuery = new SqlPageQuery<>(LoanBaseInfoEntity.class, Constant.PROCESS_DATA_LIMIT, pageIndex, sql);
			PageResult<LoanBaseInfoEntity> results = dcDao.findDataWithPage(sqlPageQuery);
			List<LoanBaseInfoEntity> baseInfoList = results.getData();
			for (LoanBaseInfoEntity loanBaseInfoEntity : baseInfoList) {
				BasicInformationAfterLoan afterLoan = new BasicInformationAfterLoan();
				afterLoan.setBillCode(loanBaseInfoEntity.getBillCode());
				afterLoan.setLoanAmount(loanBaseInfoEntity.getLoanAmount());
				//到期日为空
				if(loanBaseInfoEntity.getEndBankDate()==null){
					Calendar cal = Calendar.getInstance();
					cal.setTime(loanBaseInfoEntity.getLoanTime());
					cal.add(Calendar.MONTH, loanBaseInfoEntity.getLoanTerm());
					afterLoan.setRepayDate(cal.getTime());
					loanBaseInfoEntity.setEndBankDate(cal.getTime());
				}else{
					afterLoan.setRepayDate(loanBaseInfoEntity.getEndBankDate());
				}
				afterLoan.setRepayStatus(loanBaseInfoEntity.getRefundStatus());
				afterLoan.setSourceType(loanBaseInfoEntity.getSourceType());
				afterLoan.setLastOpDate(new Date());
				afterLoan.setOutstandingOfDeposits(refundBlanceAmount(loanBaseInfoEntity, 0));// 计算放款余额
				afterLoan.setLastYearBanlanceAmount(refundBlanceAmount(loanBaseInfoEntity, 1));
				String updateSql = "UPDATE BASIC_INFORMATION_AFTER_LOAN T SET T.LAST_OP_DATE=?,T.LOAN_AMOUNT=?,"
								+ "T.SOURCE_TYPE=?,T.REPAY_DATE=?," + "T.REPAY_STATUS=?,T.OUTSTANDING_OF_DEPOSITS=?,"
								+ "T.LAST_YEAR_BANLANCE_AMOUNT=? WHERE T.BILL_CODE=?";
				boolean flag = dcDao.excuteSql(updateSql, afterLoan.getLastOpDate(), afterLoan.getLoanAmount(), 
						afterLoan.getSourceType(), afterLoan.getRepayDate(), afterLoan.getRepayStatus(), 
						afterLoan.getOutstandingOfDeposits(), afterLoan.getLastYearBanlanceAmount(), afterLoan.getBillCode());
				if (!flag) {
					dcDao.insert(afterLoan);
					insertCount++;
				}else{
					updateCount++;
				}
			}
			pageIndex++;
			if (results.getReturnDataSize() <= pageIndex) {
				pageIndex = -1;
			}
		}
		logger.info("/****************插入贷后数据条数:[{}]******************************/", insertCount);
		logger.info("/****************更新贷后数据条数:[{}]******************************/", updateCount);
		logger.info("/****************同步贷款结束******************************/");
	}

	/**
	 * 计算 放款余额和截止去年年末余额
	 * 
	 * @param billcode
	 * @param loanAmount
	 * @param repay_status
	 * @param type
	 * @param repayDate
	 * @return
	 */
	private BigDecimal refundBlanceAmount(LoanBaseInfoEntity loanBaseInfoEntity, int type) {
		BigDecimal amount = new BigDecimal(0);
		// 1.状态为已结清的置为0
		if (!StringUtils.isEmpty(loanBaseInfoEntity.getRefundStatus()) && "CLO".equals(loanBaseInfoEntity.getRefundStatus())) {
			return amount;
		}
		// 2.到期日已到的置为0
		Date yestoday = new Date();
		if (yestoday.after(loanBaseInfoEntity.getEndBankDate())) {
			return amount;
		}
		// 3.没有还款计划就取放款金额，有还款计划就取还款计划的余额
		StringBuffer sql = new StringBuffer();
		if (type == 0) {
			sql.append("select residual_principal from  payments_plan where bill_code=? and plan_date<= curdate() order by plan_date desc limit 1 ");
		} else {
			sql.append("select residual_principal from  payments_plan where bill_code=? and  year(plan_date) <= year(date_sub(now(),interval 1 year)) order by plan_date desc limit 1 ");
		}
		PaymentsPlan entity = dcDao.findEntity(sql.toString(), PaymentsPlan.class, loanBaseInfoEntity.getBillCode());
		if (entity == null) {
			amount = loanBaseInfoEntity.getLoanAmount();
		} else {
			amount = entity.getResidualPrincipal();
		}
		return amount;
	}

	/**
	 * 更新客户贷款数据和第一次放款数据
	 */
	public void updateO2oCustomer() {
		loadCrmCustomerBaseData();
		updateLoanTimeAndNum();
		
	}
	/**
	 * 更新o2o_customer和crm客户   
	 *    贷款次数和第一次放款时间
	 */
	public void updateLoanTimeAndNum() {
		logger.info("/************************更新贷款次数和第一次放款时间开始*******************************/");
		String dcSql="SELECT T.BILL_CODE AS BILLCODE,T.CUSTOMER_ID AS CUSTOMERID,MIN(T.LOAN_TIME) AS MINLOANTIME,MAX(T.LOAN_NUM) AS LOANNUM FROM LOAN_BASE_INFO T WHERE T.LOAN_TIME IS NOT NULL  GROUP BY T.IDCARD ";
		String crmSql="UPDATE CUSTOMER_BASIC_INFO SET FIRST_LOAN_TIME=?,NUMBER_OF_LOANS=? WHERE CUSTOMER_ID=? ";
		String updateSql="UPDATE O2O_CUSTOMER SET FIRST_LOAN_TIME=?,LOAN_NUM=? WHERE CUSTOMER_ID=? ";
		List<LoanTimeNum> loanList=dcDao.findEntitys(dcSql, LoanTimeNum.class);
		for (LoanTimeNum loanTimeNum : loanList) {
			crmDao.excuteSql(crmSql,loanTimeNum.getMinLoanTime(),loanTimeNum.getLoanNum(),loanTimeNum.getCustomerId());
			dcDao.execute(updateSql,loanTimeNum.getMinLoanTime(),loanTimeNum.getLoanNum(),loanTimeNum.getCustomerId());
		}
		logger.info("/************************更新贷款次数和第一次放款时间完成*******************************/");
	}

	/**
	 * CRM客户同步到数据中心o2o_customer
	 *
	 */
	public void loadCrmCustomerBaseData() {
		logger.info("/*******************CRM客户信息同步到数据中心o2o_customer开始*****************/");
		String sql="select customer_id,customer_code,customer_name,id_type as idcard_type ,id_number as idcard ,mate_id,now() as oper_time from customer_basic_info ";
		int pageIndex = 0;
		while (pageIndex >= 0) {
			SqlPageQuery<O2oCustomer> sqlPageQuery = new SqlPageQuery<>(O2oCustomer.class, Constant.PROCESS_DATA_LIMIT,
					pageIndex, sql);
			PageResult<O2oCustomer> pageResult = crmDao.findDataWithPageForMysql(sqlPageQuery);
			for (int i = 0; i < pageResult.getReturnDataSize(); i++) {
				O2oCustomer o2oCustomer = pageResult.getData().get(i);
				try {
					int num = dcDao.findInteger("select count(1) from o2o_customer where idcard=?",
							o2oCustomer.getIdcard());
					if (num == 0) {
						dcDao.insert(o2oCustomer);
					} else {
						dcDao.updateById(o2oCustomer);
					}
				} catch (DataIntegrityViolationException e) {
					logger.error("同步CRM到数据中心异常:[{}]", e.getMessage());
				}
			}
			pageIndex++;
			if (pageResult.getReturnDataSize() <= pageIndex) {
				pageIndex = -1;
			}
		}
		logger.info("/****************CRM客户信息同步到数据中心o2o_customer完成****************/");
	}

	/**
	 * 同步逾期--更新贷后和贷前数据
	 */
	public void schroOverdue() {
		int index = 0;
		int count1 =0;
		int count2 =0;
		int count3 =0;
		int count4 =0;
		int count5 =0;
		index=0;
		String sql1="select billCode,sum(case when status='1' then defaultamount end),sum(case when status='2' then defaultamount end),sum(case when status='3' then disposalamoun end),sum(penaltyinterest),defaultdatenum from o2o_overdue_report where isnew = 'Y' group by billCode ";
		while (index >= 0) {
			logger.info("同步业务系统逾期数据第[{}]页",index);
			SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, Constant.PROCESS_DATA_LIMIT, index, sql1);
			PageResult<Object[]> pageResult = servicedao.findDataWithPage(sqlPageQuery);
			for (int i = 0; i < pageResult.getReturnDataSize(); i++) {
				Object[] obj = pageResult.getData().get(i);
					if(obj[1]!=null){
						dcDao.excuteSql("update basic_information_after_loan set overdue_interest = ?, last_op_date =sysdate() where bill_code = ?",obj[1],obj[0]);
						++count1;
					}
					if(obj[2]!=null){
						dcDao.excuteSql("update basic_information_after_loan set overdue_principal = ?, last_op_date =sysdate() where bill_code = ?",obj[2],obj[0]);
						++count2;
					}
					if(obj[3]!=null){
						dcDao.excuteSql("update basic_information_after_loan set compensatory_amount= ?, last_op_date =sysdate() where bill_code = ?",obj[3],obj[0]);
						++count3;
					}
					if(obj[4]!=null){
						dcDao.excuteSql("update basic_information_after_loan set penalty_interest= ?, last_op_date =sysdate() where bill_code = ?",obj[4],obj[0]);
						++count4;
					}
					if(obj[5]!=null){
						dcDao.excuteSql("update basic_information_after_loan set overdue_principal_days= ?, last_op_date =sysdate() where bill_code = ?",obj[5],obj[0]);
						++count5;
					}
			}
			if (pageResult.getPageTotal() > index) {
				index++;
			} else {
				index = -1;
			}
		}
		logger.info("利息逾期条数:{}",count1);
		logger.info("本金逾期条数:{}",count2);
		logger.info("代偿数:{}",count3);
		logger.info("罚息:{}",count4);
		logger.info("逾期天数:{}",count5);
	}

	/**
	 * 同步还款计划 --全量同步
	 */
	public void savePaymentPlan() {
		// 每一笔还款计划的唯一标示是refund_no，而不是bill_code，因为同一个单可能同时有两笔还款计划（银行的，怡亚通的）
		// String sql="select r.loadapplycode as bill_code ,l.refundno as
		// refund_no, l.termno as periods ,r.loanername as customer_name,
		// l.interestdate as plan_date,l.repaymentdate as
		// repayment_date,l.principalremained as residual_principal,l.isfinish
		// as is_finish,l.isexpire as is_expire,l.arprincipal as
		// pay_principal,l.arinterest as pay_interest,l.hrprincipal as
		// fact_principal,l.hrinterest as fact_interest ,r.creatorname as
		// oprate_psn ,r.createdate as oprate_time,'0' as source_type from
		// eadb.o2o_refund r inner join eadb.o2o_refundline l on r.refundno =
		// l.refundno WHERE R.islock='N' ";
		// //1.同步老系统的还款计划
		// logger.info("同步老系统的还款计划开始......");
		// try {
		// baseService.loadData(sql, PaymentsPlan.class, " delete from
		// payments_plan where source_type='0' ");
		// } catch (Exception e) {
		// logger.error("同步老系统的还款计划出现异常......");
		// throw e;
		// }
		// logger.info("同步老系统的还款计划结束......");
		// 2.同步新系统的还款计划
		logger.info("/************清空新系统还款计划***********************/");
		String delSql = "delete from payments_plan where source_type='1'";
		boolean flag = dcDao.excuteSql(delSql);
		if (flag) {
			logger.info("/***************清空新系统还款计划成功*********************/");
		}
		String sql = "select * from o2o_payments_plan t where t.is_del='N' ";
		int pageIndex = 0;
		int insertCount = 0;
		int pageSize = 100;
		while (pageIndex >= 0) {
			SqlPageQuery<O2oPaymentsPlan> sqlPageQuery = new SqlPageQuery<O2oPaymentsPlan>(O2oPaymentsPlan.class, pageSize, pageIndex, sql);
			PageResult<O2oPaymentsPlan> pageResult = servicedao.findDataWithPage(sqlPageQuery);
			for (O2oPaymentsPlan o2oPaymentsPlan : pageResult.getData()) {
				PaymentsPlan plan = new PaymentsPlan(o2oPaymentsPlan.getPaymentsId(), o2oPaymentsPlan.getBillCode(), o2oPaymentsPlan.getName(), o2oPaymentsPlan.getIdNumber(), o2oPaymentsPlan.getOpratePsn(), o2oPaymentsPlan.getOprateTime(), o2oPaymentsPlan.getPayInterest(),
						o2oPaymentsPlan.getPayPrincipal(), o2oPaymentsPlan.getPayTotal(), Integer.parseInt(String.valueOf(o2oPaymentsPlan.getPeriods())), o2oPaymentsPlan.getPaymentsDate(), o2oPaymentsPlan.getRepaymentStatus(), o2oPaymentsPlan.getResidualPrincipal(), "1");
				dcDao.insert(plan);
				insertCount++;
			}
			pageIndex++;
			if (pageResult.getPageTotal() <= pageIndex) {
				pageIndex = -1;
			}
		}
		logger.info("/***************同步还款计划更新次数:[{}]*******************/", insertCount);
		logger.info("/***************同步新系统的还款计划结束*******************/");
	}

	/**
	 * 全量同步时调用方法：删除贷前表数据、删除贷中数据、贷后数据
	 */
	public void init() {

		logger.info("/*****************开始删除贷前数据*********************/");
		String sql1 = "DELETE FROM LOAN_BASE_INFO ";
		int count1 = dcDao.execute(sql1);
		logger.info("/*****************删除贷前数据成功,删除条数:[{}]*********************/", count1);

		logger.info("/*****************开始删除贷中数据*********************/");
		String sql2 = "DELETE FROM basic_information_loan_ing ";
		int count2 = dcDao.execute(sql2);
		logger.info("/*****************删除贷中数据成功,删除条数:[{}]*********************/", count2);

		logger.info("/*****************开始删除贷后数据*********************/");
		String sql3 = "DELETE FROM basic_information_after_loan ";
		int count3 = dcDao.execute(sql3);
		logger.info("/*****************删除贷后数据成功,删除条数:[{}]*********************/", count3);
	}
}
